package com.monitor.admin.consumer;

import com.alibaba.fastjson.JSON;
import com.monitor.admin.dao.DetailMapper;
import com.monitor.admin.entity.DetailWithBLOBs;
import com.monitor.core.bean.ControllerMonitorMessage;
import com.monitor.core.bean.MonitorMessage;
import com.monitor.core.bean.MonitorType;
import com.monitor.core.util.MessageUtil;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Auther: hanhui.liu
 * @Date: 2018/4/25 10:44
 * @Description:
 */
public class ControllerConsumer implements MessageListener {
    private Logger logger = Logger.getLogger(ControllerConsumer.class);
    @Resource
    private DetailMapper detailMapper;

    @Override
    public void onMessage(Message m) {
        try {
            ControllerMonitorMessage cmm = MessageUtil.convert2ControllerMonitorMessage(m);
            DetailWithBLOBs detailWithBLOBs = new DetailWithBLOBs();
            detailWithBLOBs.setApi(cmm.getApi());
            detailWithBLOBs.setHost(cmm.getHost());
            detailWithBLOBs.setReturnValue(JSON.toJSONString(cmm.getReturnValue()));
            detailWithBLOBs.setParams(JSON.toJSONString(cmm.getParams()));
            detailWithBLOBs.setBeginTime(cmm.getBeginTime());
            detailWithBLOBs.setEndTime(cmm.getEndTime());
            detailWithBLOBs.setProcesseTime(cmm.getEndTime() - cmm.getBeginTime());
            detailWithBLOBs.setProject(cmm.getProject());
            detailWithBLOBs.setIsSuccess(cmm.isSuccess());
            if (!cmm.isSuccess()) {
                detailWithBLOBs.setException(JSON.toJSONString(cmm.getException()));
            }
            detailWithBLOBs.setType(MonitorType.Controller.value);
            detailWithBLOBs.setUri(cmm.getUri());
            detailWithBLOBs.setUuid(cmm.getUuid());
            detailWithBLOBs.setCreateTime(new Date());
            detailMapper.insert(detailWithBLOBs);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
